package de.chessgame.network;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import de.chessgame.ChessGameMod;
import de.chessgame.gui.GuiChessBoard;
import de.chessgame.tileentity.TileEntityChessBoard;

public class ChessMessageHandler implements
		IMessageHandler<ChessMessage, IMessage> {

	@Override
	public IMessage onMessage(ChessMessage message, MessageContext ctx) {
		boolean buttonPressed = message.buttonPressed;
		int data = message.data;
		int x = message.x;
		int y = message.y;
		int z = message.z;
		EntityPlayer player = ctx.getServerHandler().playerEntity;
		World world = player.getEntityWorld();
		TileEntityChessBoard tileChess = (TileEntityChessBoard) world
				.getTileEntity(x, y, z);
		if (buttonPressed) {
			switch (data) {
			case GuiChessBoard.RESET_GAME:
				tileChess.resetGame();
				break;

			case GuiChessBoard.LOCK_UNLOCK:

				boolean unlocked = false;

				if (player.getDisplayName().equals(
						tileChess.getPlayerOnWhiteLock())) {
					tileChess.setPlayerOnWhiteLock(null);
					unlocked = true;
				}

				if (player.getDisplayName().equals(
						tileChess.getPlayerOnBlackLock())) {
					tileChess.setPlayerOnBlackLock(null);
					unlocked = true;
				}
				
				if (!unlocked) {
					if (player.getDisplayName().equals(tileChess.getPlayerOnWhite())) {
						tileChess.setPlayerOnWhiteLock(player.getDisplayName());
					} else if (player.getDisplayName().equals(tileChess.getPlayerOnBlack())) {
						tileChess.setPlayerOnBlackLock(player.getDisplayName());
					}
				}
				break;

			case GuiChessBoard.QUEEN:
				tileChess.setUndefinedAsQueen();
				break;
				
			case GuiChessBoard.ROOK:
				tileChess.setUndefinedAsRook();
				break;
				
			case GuiChessBoard.KNIGHT:
				tileChess.setUndefinedAsKnight();
				break;
				
			case GuiChessBoard.BISHOP:
				tileChess.setUndefinedAsBishop();
				break;
				
			default:
				break;
			}
		} else {
			ItemStack itemStack = player.inventory.getItemStack();
			
			switch (data) {
			case GuiChessBoard.GUI_CLOSED:
				if (itemStack != null) {
					player.inventory.setItemStack((ItemStack)null);
				}
				tileChess.onGuiClosed(player);
				
			case GuiChessBoard.CLEAR_ITEMSTACK:
				player.inventory.setItemStack((ItemStack)null);
				break;
				
			default:
				break;

			}
		}
		world.markBlockForUpdate(x, y, z);
		return null;
	}
}
